#!/bin/bash

target_branch="openEuler-22.03-LTS-SP4"
target_branch_ros="Multi-Version_ros-humble_openEuler-22.03-LTS-SP2"
force_makediff="true"

black_list=`cat black.repo`
infos=`python format_info.py`
for info in $infos;
do
    reponame=$(echo $info | awk -F '#' '{print $1}')
    url=$(echo $info | awk -F '#' '{print $2}')
    basecommit=$(echo $info | awk -F '#' '{print $3}')

    # cross black list. no need to analyse
    is_black=0
    for item in $black_list;
    do
        if [ "$item" == "$reponame" ]; then
            is_black=1
            continue
        fi
    done
    if [ "$is_black" == "1" ]; then
        continue
    fi
    

    if [ -e src_tmp/$reponame/filelock.$basecommit ];then
        # not clean, remove it
        rm -rf src_tmp/$reponame
    fi 
    if [ "$force_makediff" == "false" ];then
        if [ -d src_tmp/$reponame ];then
            # already done, go cross it
            continue
        fi
    fi

    mkdir -p src_tmp/$reponame; cd src_tmp/$reponame
    touch filelock.$basecommit
    git remote -vv | grep upstream | grep "$url"
    if [ ! "$?" == "0" ];then
        echo "---------init baseline of $url------------"
        git init .  ; git remote add upstream $url
        git fetch upstream $basecommit --depth=1
        git checkout $basecommit
    fi
    git fetch upstream $target_branch --depth=1
    if [ "$?" == "0" ];then
        echo "$target_branch" > ${reponame}.oe.specdiff
        lastcommit=$(git rev-parse upstream/$target_branch)
        echo $lastcommit >> ${reponame}.oe.specdiff
        git diff $basecommit upstream/$target_branch *spec  >> ${reponame}.oe.specdiff
        if [ $(wc -l < ${reponame}.oe.specdiff) -eq 2 ]; then
            echo "无差异" >> ${reponame}.oe.specdiff
        fi
    else
        git fetch upstream $target_branch_ros --depth=1
        if [ "$?" == "0" ];then
            echo "$target_branch_ros" > ${reponame}.oe.specdiff
            lastcommit=$(git rev-parse upstream/$target_branch_ros)
            echo $lastcommit >> ${reponame}.oe.specdiff
            git diff $basecommit upstream/$target_branch_ros *spec  >> ${reponame}.oe.specdiff
            if [ $(wc -l < ${reponame}.oe.specdiff) -eq 2 ]; then
                echo "无差异" >> ${reponame}.oe.specdiff
            fi
        else
            echo "目标分支不存在" > ${reponame}.oe.specdiff
            echo "目标commit未知" >> ${reponame}.oe.specdiff
            echo "差异未知" >> ${reponame}.oe.specdiff
        fi
    fi
    rm filelock.$basecommit
    cd -

done

